/**
 * Created by Adi(adi@imeth.cn) on 2018/8/31.
 */
import React from 'react';
import { Form, Button, Dropdown, Icon, Row, Col, DatePicker } from 'antd';
import { autobind } from 'core-decorators';
import PropTypes from 'prop-types';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;

@Form.create()
@autobind
class QueryData extends React.Component {
  static propTypes = {
    shrink: PropTypes.bool,
    queryList: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number,
      PropTypes.element,
      PropTypes.array,
    ]), // 渲染查询列表
    operateExtra: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.element]), // 渲染按钮内容
    selectedRows: PropTypes.array, // 选中行 (批量操作)
    menuExtra: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.element]), // 渲染批量操作内容
    onQuery: PropTypes.func,
  };

  static defaultProps = {
    shrink: true,
    selectedRows: [],
    queryList: [],
  };

  constructor(props) {
    super(props);
    let { form, shrink, queryList } = this.props;
    let showShrink = queryList.length > 6;
    this.state = {
      shrink,
      formValues: {},
      form,
      showShrink,
      beginTime: null,
      endTime: null,
    };
  }

  // react16.3新生命周期 接受props 修改state 返回类似setState()
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.shrink === prevState.shrink) {
      // 返回Null 不修改state
      return null;
    }
    return {
      shrink: prevState.shrink,
    };
  }

  // 遍历渲染每一项查询
  renderSearch() {
    let { form, queryList } = this.props;
    let { getFieldDecorator } = form;
    let { shrink } = this.state;
    let allSearchList = [];
    for (let i = 0; i < queryList.length; i++) {
      if (queryList[i].value === 'queryTime') {
        allSearchList.push(
          <Col key={i} span={8}>
            <FormItem style={{ display: 'flex' }}>
              {getFieldDecorator(queryList[i].value)(
                <RangePicker
                  showTime={{ format: 'HH:mm' }}
                  format="YYYY-MM-DD HH:mm"
                  placeholder={['开始时间', '结束时间']}
                  // onChange={(value, dateString) => console.info('value', value, 'data', dateString)}
                  onChange={(value, dateString) =>
                    this.setState({ beginTime: dateString[0], endTime: dateString[1] })
                  }
                />
              )}
            </FormItem>
          </Col>
        );
        continue;
      }
      allSearchList.push(
        <Col key={i} span={4}>
          <FormItem style={{ display: 'flex' }}>
            {getFieldDecorator(queryList[i].value)(queryList[i].renderItem)}
          </FormItem>
        </Col>
      );
    }

    let searchList = shrink ? allSearchList.splice(0, 6) : allSearchList;
    return searchList;
  }

  render() {
    let { operateExtra, selectedRows, menuExtra, queryList } = this.props;
    let { shrink, showShrink } = this.state;
    return (
      <Form onSubmit={event => this._onValidate(event)}>
        <Row type="flex" justify="start" align="middle">
          {this.renderSearch()}
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <span>
            {operateExtra}
            {/*若没有批量操作则可删除*/}
            {selectedRows.length > 0 && (
              <span>
                <Dropdown overlay={menuExtra}>
                  <Button>
                    批量操作 <Icon type="down" />
                  </Button>
                </Dropdown>
              </span>
            )}
          </span>
          {queryList.length !== 0 && (
            <span style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetForm}>
                重置
              </Button>
              {showShrink && (
                <a style={{ marginLeft: 8 }} onClick={() => this.setState({ shrink: !shrink })}>
                  {shrink ? (
                    <span>
                      展开 <Icon type="down" />
                    </span>
                  ) : (
                    <span>
                      收起 <Icon type="up" />
                    </span>
                  )}
                </a>
              )}
            </span>
          )}
        </div>
      </Form>
    );
  }

  // 表单校验以及赋值
  _onValidate(event) {
    event.preventDefault();
    const { form } = this.state;
    form.validateFields((error, formValues) => {
      if (error) return;
      this.setState({ formValues }, this._onQuery);
    });
  }

  // 表单重置
  resetForm() {
    const { form } = this.state;
    // 重置表单
    form.resetFields();
    this.setState({
      formValues: {},
    });
  }

  // 查询方法
  _onQuery() {
    let { onQuery } = this.props;
    let { formValues, beginTime, endTime } = this.state;
    beginTime ? (formValues['beginTime'] = beginTime) : formValues;
    endTime ? (formValues['endTime'] = endTime) : formValues;
    onQuery && onQuery(formValues);
  }
}

export default QueryData;
